<?php
/**
 * Created by PhpStorm.
 * User: zyh
 * Date: 2018/5/25
 * Time: 下午11:39
 */

namespace app\admin\controller;



use app\admin\model\Rewards;
use GatewayClient\Gateway;
use think\Cache;
use think\Controller;
use think\Exception;

class Game extends Base
{

    public function game_source()
    {
        $game = new \app\admin\model\Game();
        $games = $game->all();
        $rewards = new Rewards();
        foreach ($games as $k=>$game){
            $r = $rewards->where(['gid'=>$game['id']])->distinct(true)->field('uid')->select();
            $games[$k]['part'] = count($r);
        }
        return ['status'=>1,"data"=>$games];
    }

    public function game_list()
    {
        return view();
    }

//    开始游戏 新建游戏ID
    public function newgame()
    {
        $game = new \app\admin\model\Game();
        if ($post = input("post.")){
            if ($game::where("status",">",-1)->select()){
                return ['status'=>0,'info'=>"当前有比赛还未结束 不能创建新的比赛"];
            }
            $id = input("post.id");
            $start_time = input("post.start_time");

            $id = $game->save(['id'=>$id,'start_time'=>$start_time]);
            Gateway::sendToGroup("user",base64_encode('{"type":"refresh"}'));
            //清除保存的扣 多余
            Cache::rm("kou");
            //增加最新一句的战况

            $reset = input("post.reset");
            if ($reset){
                Cache::set("winners",[]);
            }

            $time = strtotime(date("Y-m-d"),time())+86400 - time();//今天剩余时间
            $winners = Cache::get("winners",[]);
            array_push($winners,-1);//-1 显示为进行中
            Cache::set("winners",$winners,$time);

            return ['status'=>1,'id'=>$game->getLastInsID()];
        }
        $id = $game->field('id')->order('id','desc')->find();
        $this->assign("id",$id['id']?$id['id']+1:1000);
        $this->assign("start_time",date("Y-m-d H:i:s"));
        return view();

    }

//    开始游戏详情  重点
    public function game_start()
    {
        $system = \app\admin\model\System::getSystem();
        $this->assign("system",$system);
        $id = input()['id'];
        $this->assign("game_id",$id);
        return view();
    }

    public function test()
    {
        $b=[2,1,1,-1];
        Cache::set('winners',$b);
        $a = Cache::get('winners');
        print_r($a);
    }

    public function test1()
    {
        $rewards = new Rewards();
        $a = $rewards->calToScore(10,7,1,2);
        echo $a;
    }
}